﻿using Microsoft.Extensions.Hosting;

namespace Basic.ScheduledTask.Abstract
{
    public abstract class ScheduledBackgroundService : BackgroundService
    {
        protected IJobManager JobManager { get; }

        protected abstract string CronExpression { get; }

        public ScheduledBackgroundService(IJobManager jobManager)
        {
            JobManager = jobManager;
        }

        public abstract Task ScheduledJob(CancellationToken stoppingToken);

        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            string jobName = this.GetType().FullName ?? this.GetType().GUID.ToString();
            JobManager.AddRecurringJob(jobName, () => ScheduledJob(CancellationToken.None), CronExpression);
            return Task.CompletedTask;
        }

    }
}